<template>
    <div class="component-upload-image">
        <a-upload :disabled=disabled :action="uploadImgUrl" :list-type="'picture-card'" :before-upload="handleBeforeUpload"
            :file-list="fileList" :max-count="limit" :show-file-list="true" :headers="headers" name="files"
            ref="imageUpload" accept="image/jpeg,image/png,image/jpg" @change="handleChange">
            <div v-if="fileList.length < limit">
                <a-icon type="upload" />
                <div style="margin-top: 8px">上传</div>
            </div>
        </a-upload>
        <!-- 上传提示 -->
        <!-- <div class="el-upload__tip" v-if="showTip">
            请上传
            <template v-if="fileSize">
                大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
            </template>
<template v-if="fileType">
                格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
            </template>
的文件
</div> -->
    </div>
</template>

<script>
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
    props: {
        value: {
            type: [String, Object, Array],
        },
        limit: {
            type: Number,
            default: 5,
        },
        // 大小限制(MB)
        fileSize: {
            type: Number,
            default: 100,
        },
        // 文件类型, 例如['png', 'jpg', 'jpeg']
        fileType: {
            type: Array,
            default: () => ["png", "jpg", "jpeg"],
        },
        // 是否显示提示
        isShowTip: {
            type: Boolean,
            default: true,
        },
        disabled:{
            type: Boolean,
            default: false,
        }
    },
    data() {
        return {
            number: 0,
            uploadList: [],
            dialogImageUrl: undefined,
            uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/uploads',
            baseUrl: process.env.VUE_APP_BASE_API,
            headers: {
                Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
            },
            fileList: undefined,
            hide: undefined
        }
    },
    watch: {
        value: {
            handler(val) {
                this.handleValueChange(val);
            },
            immediate: true, // 监听器会在初始化时立即执行
        },
    },
    computed: {
        showTip: function () {
            return this.isShowTip && (this.fileType.length > 0 || this.fileSize);
        }
    },
    methods: {
        handleValueChange(val) {
            if (val) {
                // 首先将值转为数组
                const list = Array.isArray(val) ? val : val.split(",");
                // 然后将数组转为对象数组
                this.fileList = list.map((item,index) => {
                    if (typeof item === "string") {
                        // if (item.indexOf(this.baseUrl) === -1) {
                        //     item = { name: this.baseUrl + item, url: this.baseUrl + item };
                        // } else {
                        //     item = { name: item, url: item };
                        // }
                        item = { name: item, url: item, status: 'done',uid:index};
                    }
                    return item;
                });
            } else {
                this.fileList = [];
            }
        },
        // hide() {

        // },
        handleBeforeUpload(file) {
            let isImg = false;
            if (this.fileType.length) {
                let fileExtension = "";
                if (file.name.lastIndexOf(".") > -1) {
                    fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
                }
                isImg = this.fileType.some((type) => {
                    if (file.type.indexOf(type) > -1) return true;
                    if (fileExtension && fileExtension.indexOf(type) > -1) return true;
                    return false;
                });
            } else {
                isImg = file.type.indexOf("image") > -1;
            }

            if (!isImg) {
                this.$message.error(
                    `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
                );
                return false;
            }
            if (this.fileSize) {
                const isLt = file.size / 1024 / 1024 < this.fileSize;
                if (!isLt) {
                    this.$message.error(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
                    return false;
                }
            }
            // this.hide = this.$message.loading("正在上传文件，请稍候...", 0);
            this.number++;
        },
        uploadedSuccessfully() {
            if (this.number > 0 && this.uploadList.length === this.number) {
                // this.fileList = this.fileList.concat(this.uploadList);
                this.uploadList = [];
                this.number = 0;
                this.$emit("input", this.listToString(this.fileList));
            }
        },
        listToString(list, separator) {
            let strs = "";
            separator = separator || ",";
            for (let i in list) {
                if (list[i].url) {
                    strs += list[i].url.replace(this.baseUrl, "") + separator;
                }
            }
            return strs != "" ? strs.substr(0, strs.length - 1) : "";
        },
        async handleChange(info) {
            // if (info.file.status === 'uploading') {
            //     this.loading = true
            //     return
            // }
            this.fileList = [...info.fileList]

            if (info.file.status === 'done') {
                if (info.file.response.code !== 200) {
                    this.$message.error('上传失败' + info.file.response.msg)
                    this.loading = false
                    this.number--;
                    this.uploadedSuccessfully();
                    return
                }
                this.uploadList.push({ name: info.file.response.fileNames, url: info.file.response.fileNames });
                this.$message.success({ content: "上传成功" });
                let fileList = this.fileList.map(file => {
                    if (file.response) {
                        // Component will show file.url as link
                        file.url = file.response.urls;
                    }
                    return file;
                });
                this.fileList = fileList;
                this.uploadedSuccessfully();
            }
        },
    },




}
</script>

<style lang="scss" scoped></style>